package simkuenzi.catchme;
import java.util.List;
import java.util.ArrayList;

public class Game {
	private GameObject player;
	private static  final int DELAY=10;
	private static final int SPEED=1;
	private float acclX;
	private float acclY;
	private boolean running;
	private List<GameListener> listeners = new ArrayList<GameListener>();

	private GameObject target;
	private int width, height;
	private boolean success;

	public Game(GameObject player, GameObject target) {
		this.player = player;
		this.target = target;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getWidth() {
		return width;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getHeight() {
		return height;
	}

	public void setPlayer(GameObject player) {
		this.player = player;
	}

	public GameObject getPlayer() {
		return player;
	}

	public void setTarget(GameObject target) {
		this.target = target;
	}

	public GameObject getTarget() {
		return target;
	}

	public static Game createDefault() {
		GameObject player = new GameObject(0, 0, 30);
		GameObject target = new GameObject(100, 200, 40);
		return new Game(player, target);


	}


	public void control(float x, float y) {
		acclX = x;
		acclY = y;
	}

	public void run() {
		synchronized (this) {
			if (running) {
				return;
			} else {
				running = true;
			}
		}

		Runnable r = new Runnable() {
			public void run() {
				while (running) {
					int x = player.getX();
					int y = player.getY();
					x += acclX * -1 * SPEED;//<0?SPEED:-1*SPEED;
					y += acclY * SPEED;//<0?SPEED:-1*SPEED;

					x = Math.max(0, x);
					x = Math.min(width - player.getSize(), x);
					y = Math.max(0, y);
					y = Math.min(height - player.getSize(), y);

					player.setX(x);
					player.setY(y);
					if (within(x, y, player.getSize(), target.getX(), target.getY(), target.getSize())) {
						success = true;
					}

					onChanged();

					try {
						Thread.sleep(DELAY);
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
				}
			}
		};

		Thread t = new Thread(r);
		t.start();
	}

	public void pause() {
		running = false;
	}

	public void addListener(GameListener listener) {
		listeners.add(listener);
	}

	private void onChanged() {
		for (GameListener listener : listeners) {
			listener.changed();
		}
	}

	private static boolean within(int xa, int ya, int sa, int xb, int yb, int sb) {
		return
			between(xa, xb, xb + sb) &&
			between(xa + sa, xb, xb + sb) &&
			between(ya, yb, yb + sb) &&
			between(ya + sa, yb, yb + sb);
	}

	private static boolean between(int v, int a, int b) {
		return
			v >= a && v <= b;
	}

}
